<template>
    <page-box class="custom-page-box">
        <template v-slot:header>
            <ask-breadcrumb>
                <template v-for="(item, index) in $getBreadCrumbsName($route.path)">
                    <ask-breadcrumb-item :key="index" v-if="item.path" :to="'/' + item.path">{{ item.meta.title }}</ask-breadcrumb-item>
                    <ask-breadcrumb-item :key="index" v-else>{{ item.meta.title }}</ask-breadcrumb-item>
                </template>
            </ask-breadcrumb>
        </template>
        <div class="org-container">
            <div class="container-left">
                <div class="container-left-body">
                    <div class="scroll-box">
                        <type-tree
                            ref="TypeTree"
                            @clickNode="clickNode"
                        ></type-tree>
                    </div>
                </div>
            </div>
            <div class="container-right">
                <page-search>
                    <page-search-column class="fixed-column">
                        <page-search-item>
                            <el-button type="primary" @click="toAddForm">添加上报</el-button>
                        </page-search-item>
                        <page-search-item>
                            <el-button @click="toCopyForm">复制已有表单</el-button>
                        </page-search-item>
                        <page-search-item>
                            <el-button @click="showImg">小程序端预览</el-button>
                        </page-search-item>
                    </page-search-column>
                </page-search>
                <div class="container-right-body">
                    <el-table
                        v-show="tableData.length"
                        :data="tableData"
                        class="org-table pbb__table"
                        header-cell-class-name="pbb__table-thead"
                        cell-class-name="pbb__table-thead-cell"
                        row-class-name="pbb__table-thead-row"
                        ref="multipleTable"
                        style="width: 100%;height: 100%;overflow-y: auto;">
                        <el-table-column
                            label="序号"
                            align="center"
                            type="index"
                            width="60">
                        </el-table-column>
                        <el-table-column
                            prop="formName"
                            label="表单名称">
                        </el-table-column>
                        <el-table-column
                            prop="categoryName"
                            label="分类">
                        </el-table-column>
                        <el-table-column
                            prop="receiverName"
                            label="接收人">
                        </el-table-column>
                        <el-table-column
                            prop="status"
                            label="状态"
                            width="80">
                            <template slot-scope="scope">
                                <span :class="scope.row.status === 1 ? 'green' : 'red'">{{ scope.row.status === 1 ? "已发布" : "草稿" }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column
                            prop="createTime"
                            label="添加时间">
                        </el-table-column>
                        <el-table-column
                            label="操作"
                            class-name="operate"
                            width="180">
                            <template slot-scope="scope">
                                <el-button v-if="scope.row.status === 1" size="mini" type="text" @click="changeReceiver(scope.row)">接收人</el-button>
                                <el-button v-if="scope.row.status === 1" size="mini" type="text" @click="changeType(scope.row)">分类</el-button>
                                <el-button v-if="scope.row.status !== 1" size="mini" type="text" @click="toEdit(scope.row)">编辑</el-button>
                                <el-button size="mini" type="text" @click="toDelete(scope.row)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <ask-empty-text
                        style="min-height: 300px;"
                        v-if="tableData.length === 0"
                    >
                    </ask-empty-text>
                </div>
                <div class="page-base-footer">
                    <pagination :total="total" :page.sync="pageIndex" :limit.sync="pageSize" @pagination="getTable"/>
                </div>
            </div>
        </div>
        <el-dialog
            :visible.sync="dialogVisible"
            custom-class="set-department"
            :destroy-on-close="true"
            :append-to-body="true"
            title="设置分类"
            center
            width="30%">
            <div class="set-department-container">
                <el-select v-model="setTypeId"  placeholder="请选择分类">
                    <el-option
                      v-for="item in typeOptions"
                      :key="item.id"
                      :value="item.id"
                      :label="item.name"
                    >
                      {{ item.name }}
                    </el-option>
                </el-select>
            </div>
            <div slot="footer" class="dialog-footer set-department-footer">
                <el-button @click="closeSetType">取 消</el-button>
                <el-button type="primary" @click="saveSetType">确 定</el-button>
            </div>
        </el-dialog>
        <el-dialog
            :visible.sync="showImgVisible"
            width="25%"
            :close-on-click-modal="false"
            class="img-dialog"
        >
            <img src="~@/assets/wechatImg.png" alt="logo">
        </el-dialog>
    </page-box>
</template>

<script lang="ts">
import Vue from "vue";
import { Component } from "vue-property-decorator";
import TypeTree from "@/views/declare-manage/src/components/type-tree/index.vue";
import { dialogSelect } from "@/views/process-manage/src/components/person-selection/index";
import { State } from "vuex-class";

@Component({
    components: {
        TypeTree
    }
})
export default class DeclareConfig extends Vue {
    @State(state => state.user.userInfo) user: any;

    // 数据总数
    total = 0;
    // 每页数量
    pageSize = 10;
    // 当前页码
    pageIndex = 1;
    // 表格数据
    tableData = [];
    // 所有子级的分类
    categoryId = ""
    // 当前真正的分类
    reallyCategoryId = ""
    dialogVisible = false
    // 当前表单信息
    nowTypeNode: any = {}
    setTypeId = ""
    typeOptions: any[] = []
    showImgVisible = false

    created() {
        this.initPage();
    }

    activated() {
        this.getTable();
        if (!this.categoryId) {
            (this.$refs.TypeTree as any).getType("update");
        }
    }

    // 初始化传值的数据
    initPage() {
        this.total = 0;
        this.pageSize = 10;
        this.pageIndex = 1;
        this.tableData = [];
    }

    showImg() {
        this.showImgVisible = true;
    }

    // 点击节点获取列表
    clickNode(data: any) {
        if (this.reallyCategoryId !== data.id) {
            (this.$refs.multipleTable as any).clearSelection();
        }
        this.reallyCategoryId = data.id;
        // this.categoryId = data.ids;
        this.getTable();
    }

    // 获取表格数据
    async getTable() {
        const res = await this.$server["declare/typeForm/list"]({
            data: {
                pageSize: this.pageSize,
                currentPage: this.pageIndex,
                categoryIds: this.reallyCategoryId
            }
        });
        if (res.data.code === 200) {
            this.tableData = res.data.data.records;
            this.total = res.data.data.total;
        } else {
            this.$message.error(res.data.message || "接口请求错误!");
        }
    }

    toAddForm() {
        const count = (this.$refs.TypeTree as any).treeData[0].count;
        if (count >= 50) {
            this.$message.error("上报列表表单数已满50， 请前往清理后再做添加");
            return;
        }
        this.$router.push({
            name: "TownAdminModuleManageForm",
            query: {
                declareTypeId: this.reallyCategoryId
            }
        });
    }

    // 复制已有表单
    toCopyForm() {
        const count = (this.$refs.TypeTree as any).treeData[0].count;
        if (count >= 50) {
            this.$message.error("上报列表表单数已满50， 请前往清理后再做添加");
            return;
        }
        dialogSelect({
            isSingle: true,
            title: "表单选择",
            tabs: [
                {
                    label: "科室表单",
                    name: "department"
                },
                {
                    label: "区县表单",
                    name: "regional"
                },
                {
                    label: "平台表单",
                    name: "operation"
                }
            ],
            sure: async(vm: any, model: any) => {
                vm.close();
                if (model.selectedList.length) {
                    this.$router.push({
                        name: "TownAdminModuleManageForm",
                        query: {
                            id: model.selectedList[0],
                            isCopy: "copy",
                            declareTypeId: this.reallyCategoryId
                        }
                    });
                }
            },
            getOptions: (vm: any, model: any) => this.getFormOptions(vm, model)
        });
    }

    // 获取表单列表
    async getFormOptions(vm: any, model: any) {
        const { name } = model;
        const res = await this.$server["moduleManage/norm-list/list"]({
            data: {
                currentPage: 1,
                pageSize: 99999,
                formKind: name === "department" ? 2 : name === "regional" ? 4 : 1
            }
        });
        if (res.data.code === 200) {
            vm.getOptions(res.data.data.records || []);
        } else {
            this.$message.error(res.data.message || "接口请求错误!");
        }
    }

    changeReceiver(row: any) {
        dialogSelect({
            isSingle: true,
            selectedList: [row.receiverId],
            selectedItemList: [{ id: row.receiverId, name: row.receiverName }],
            tabs: [
                {
                    label: "镇成员",
                    name: "town",
                    type: "group"
                }
            ],
            sure: async(vm: any, model: any) => {
                vm.close();
                if (model.selectedList.length && model.selectedList[0] !== row.receiverId) {
                    this.toChange(row, { receiverId: model.selectedList[0] });
                }
            },
            getOptions: (vm: any, model: any) => this.getOptions(vm, model)
        });
    }

    async toChange(row: any, data: any) {
        const res = await this.$server["declare/changeReceiveOrCategory"]({
            data: {
                id: row.id,
                receiverId: data.receiverId || row.receiverId,
                categoryId: data.categoryId || row.categoryId
            }
        });
        if (res.data.code === 200) {
            this.$message.success("修改成功");
            this.closeSetType();
            this.getTable();
            (this.$refs.TypeTree as any).getType("update");
        } else {
            this.$message.error(res.data.message || "接口请求错误!");
        }
    }

    // 获取选项
    async getOptions(vm: any, model: any) {
        if (model.name === "town") {
            const res = await this.$server["org/getMember"]({
                data: {
                    departmentId: "",
                    pageSize: 999,
                    currentPage: 1
                },
                loader: false
            });
            if (res.data.code === 200) {
                const arrObj: any = {};
                res.data.data.records.filter((item: any) => item.id !== this.user.id).forEach((item: any) => {
                    if (arrObj[item.departmentId]) {
                        arrObj[item.departmentId].push({
                            ...item,
                            governmentName: item.departmentName
                        });
                    } else {
                        arrObj[item.departmentId] = [{
                            ...item,
                            governmentName: item.departmentName
                        }];
                    }
                });
                vm.getOptions(Object.values(arrObj) || []);
            } else {
                vm.getOptions([]);
            }
        }
    }

    changeType(row: any) {
        this.dialogVisible = true;
        this.nowTypeNode = row;
        this.setTypeId = String(row.categoryId);
        this.typeOptions = (this.$refs.TypeTree as any).treeData[0].children;
    }

    closeSetType() {
        this.dialogVisible = false;
        this.setTypeId = "";
    }

    // 修改表单分类
    saveSetType() {
        if (Number(this.setTypeId) === this.nowTypeNode.categoryId) return false;
        this.toChange(this.nowTypeNode, { categoryId: this.setTypeId });
    }

    toEdit(row: any) {
        this.$router.push({
            name: "TownAdminModuleManageForm",
            query: {
                declareTypeId: row.categoryId,
                id: row.formId,
                rowId: row.id,
                receiverId: row.receiverId,
                receiverName: row.receiverName
            }
        });
    }

    toDelete(row: any) {
        this.$confirm("是否确认删除当前上报表单?", "删除")
            .then(async() => {
                const res = await this.$server["declare/deleteForm"]({
                    data: {
                        id: row.id
                    }
                });
                if (res.data.code === 200) {
                    this.$message.success("删除成功");
                    this.getTable();
                    (this.$refs.TypeTree as any).getType("update");
                } else {
                    this.$message.error(res.data.message || "接口请求错误!");
                }
            })
            .catch();
    }
}
</script>

<style scoped lang="scss">
.org-container {
    display: flex;
    flex-flow: row nowrap;
    height: 100%;
    .container-left {
        width: 3rem;
        flex: 0 0 auto;
        .filter-input {
            width: 1.3rem;
            margin-right: 10px;
        }
        .container-left-body {
            background: #fff;
            margin-left: 4px;
            height: 100%;
            padding: 10px;
            .add-btn {
                float: right;
                margin-bottom: 14px;
            }

            .scroll-box {
                max-height: 100%;
                overflow-y: auto;
                clear: both;
            }
        }
    }
    .container-right {
        margin-left: 0.1rem;
        width: calc(100% - 3.1rem);
        height: calc(100% - 8px);
        .container-right-body {
            height: calc(100% - 120px);
            margin-top: 10px;
        }
        .pbf-pagination {
            margin-top: 0.2rem;
            text-align: right;
        }
        .change-password-container {
            margin: 0;
        }
    }
}
.set-department {
    ::v-deep {
        .el-dialog__body {
            padding-top: 0;
        }
    }
    .set-department-container {
        width: 80%;
        margin: 0 auto;
            ::v-deep {
                .el-select {
                    width: 100%;
                }
            }
    }
}
</style>
<style lang="scss" scoped>
::v-deep {
    .page-base-body {
        height: calc(100% - 50px) !important;
    }
    .page-base-footer {
        width: 100%;
        min-width: unset !important;
    }
}
.change-password-container {
    margin-top: 0.6rem;
    .title {
        text-align: center;
        margin-bottom: 0.3rem;
        span {
            display: inline-block;
            font-size: 0.22rem;
            font-weight: 600;
            text-align: center;
            padding-bottom: 0.04rem;
            border-bottom: 2px solid $password-confirm-prompt-text;
        }
    }
    .change-password-form {
        width: 4rem;
        margin: 0 auto;
        ::v-deep {
            .cf__group {
                padding-bottom: 0.1rem;
            }
            .cf__group.error {
                padding-bottom: 0.3rem;
            }
            .cf__group-info {
                display: flex;
                justify-content: flex-start;
                align-items: center;
                border-bottom: 1px solid #dcdcdc;
                i {
                    font-size: 0.18rem;
                    color: $password-confirm-prompt-text;
                }
                .el-input__inner {
                    border: 0;
                    border-radius: 0;
                    line-height: 0.14rem;
                    font-size: 0.14rem;
                    padding-left: 0.1rem;
                    border-left: 1px solid $password-confirm-prompt-text;
                    height: 0.14rem;
                    margin-left: 0.1rem;
                    width: 100%;
                }
                .el-input__suffix {
                    right: 16px;
                }
            }
            .cf__group-tips {
                bottom: 0;
            }
        }
    }
}
::v-deep {
    .reset-popup.el-dialog {
        width: 4rem;
        .resetPassword-btn {
            text-align: right;
            padding-top: 0.1rem;
        }
        .change-password-container .change-password-form {
            width: 90%;
            padding: 0;
        }
    }
}

.set-department-footer {
    padding-right: 44px;
}
.img-dialog {
    img {
        display: block;
        width: 100%;
    }
}

.pbb__table {
    .green {
        color: #32A78F;
    }
    .red {
        color: #de2728;
    }
    .yellow {
        color: #f3c14f;
    }
    .blue {
        color: #2c82c9;
    }
}
</style>
